<template>
  <div class="cart-page">
    <Header @search="handleSearch" />
    <div class="cart-container">
      <ProductList
        :products="filteredProducts"
        @update="updateQuantity"
        @remove="removeProduct"
        @toggle-select="toggleSelect"
        @toggle-select-all="toggleSelectAll"
        @toggle-favorite="toggleFavorite"
      />
      <CheckoutSummary
        :products="filteredProducts"
        :discount="discount"
        @checkout="handleCheckout"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import Header from './CartHeader.vue'
import ProductList from './ProductList.vue'
import CheckoutSummary from './CheckoutSummary.vue'
import { ElMessage } from 'element-plus'
import axios from 'axios' // 引入axios库，确保已安装
// import router from 'vue-router'

const products = ref([])
const discount = ref(0)
const searchQuery = ref('')

// 获取购物车数据
async function getCartItems () {
  try {
    const userName = 'admin'
    const response = await axios.get(`/cart/list/${userName}`)
    products.value = response.data.map(item => ({
      userName: userName,
      itemId: item.itemId,
      itemTitle: item.itemTitle,
      quantity: item.quantity,
      price: item.price,
      status: item.status,
      selected: false,
      favorite: false
    }))
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    products.value = [] // 设置为空数组而不是显示错误消息
  }
}

const filteredProducts = computed(() => {
  if (!searchQuery.value) return products.value
  return products.value.filter(product =>
    product.itemTitle.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// const updateQuantity = async (itemId, quantity) => {
//   console.log('Updating quantity for item ID:', itemId, 'to:', quantity) // 添加调试信息
//
//   try {
//     const response = await axios.put(`/cart/update/${itemId}`, { quantity })
//     console.log('Quantity updated successfully:', response.data)// 成功更新后的调试信息
//     ElMessage.success('数量更新成功')
//   } catch (error) {
//     if (error.response && error.response.status === 401) {
//       ElMessage.warning('请先登录')
//       router.push('/login')
//     } else if (error.response && error.response.status === 405) {
//       ElMessage.error('请求方法不被允许，请稍后重试')
//       console.error('请求方法不被允许响应:', error.response.data) // 添加调试信息
//     } else {
//       ElMessage.error('更新数量失败，请稍后重试')
//       console.error('更新数量失败:', error) // 添加调试信息
//     }
//   }
// }

function removeProduct (itemId) {
  // 移除商品并更新本地状态
  products.value = products.value.filter(p => p.itemId !== itemId)

  // 给用户成功的反馈
  ElMessage.success('商品已移除')
}

// 收藏商品
async function toggleFavorite (itemId) {
  try {
    const product = products.value.find(p => p.id === itemId)
    if (product) {
      if (product.favorite) {
        await axios.post('/logic/favorites/remove', { itemId: itemId })
      } else {
        await axios.post('/logic/favorites/add', { itemId: itemId }
        )
      }
      product.favorite = !product.favorite
      ElMessage.success(product.favorite ? '已加入收藏' : '已取消收藏')
    }
  } catch (error) {
    console.error('操作收藏失败:', error)
    ElMessage.error('操作收藏失败')
  }
}

// 结算
async function handleCheckout () {
  try {
    const selectedProducts = products.value.filter(p => p.selected)
    if (selectedProducts.length === 0) {
      ElMessage.warning('请选择要结算的商品')
      return
    }
    await axios.post('/orders/create', {
      items: selectedProducts.map(p => ({
        itemId: p.id,
        quantity: p.quantity
      }))
    })
    ElMessage.success('下单成功')
    getCartItems() // 刷新购物车数据
  } catch (error) {
    console.error('结算失败:', error)
    ElMessage.error('结算失败')
  }
}

function handleSearch (query) {
  console.log('搜索:', query)
  searchQuery.value = query
}

function toggleSelect (id) {
  const product = products.value.find(p => p.id === id)
  if (product) {
    product.selected = !product.selected
  }
}

function toggleSelectAll (selected) {
  products.value.forEach(p => {
    p.selected = selected
  })
}

onMounted(() => {
  getCartItems()
})
</script>

<style scoped>
.cart-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.cart-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: flex;
  gap: 20px;
}
</style>
